package code._13io.other._04serialize;

import java.io.*;

public class Demo2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        serialize2();

        unSerialize2();
    }

    private static void serialize2() throws IOException {
        // 创建序列化流对象
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("a.txt"));

        // 创建Teacher对象
        Teacher t1 = new Teacher("zs", 20);
        Teacher t2 = new Teacher("ls", 21);
        Teacher t3 = new Teacher("ww", 22);
        Teacher t4 = new Teacher("zl", 23);
        Teacher[] teachers = {t1, t2, t3, t4};

        out.writeObject(teachers);

        out.close();

    }

    private static void unSerialize2() throws IOException, ClassNotFoundException {
        // 创建反序列化流对象
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("a.txt"));
        // readObject
        Teacher[] teachers = (Teacher[]) in.readObject();

        for (Teacher teacher : teachers) {
            System.out.println(teacher);
        }

        // close
        in.close();
    }
}

class Teacher implements Serializable {

    // 自动添加serialVersionUID字段
    private static final long serialVersionUID = -3591719439133395280L;
    String name;
    int age;

    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
